﻿using System;
using Core.Authenticated;
using Core.Library;
using DataObject.Online;

namespace CMS.Controls.Online
{
    public partial class CreateOrEdit : AuthenticatedControl
    {
        protected int OnlineId;
        protected void Page_Load(object sender, EventArgs e)
        {
            OnlineId = Utils.GetIdFromRequestString(Utils.OnlineId, 0);

            if (!IsPostBack)
            {
                ltTitle.Text = "Tạo mới thông tin online";

                if (OnlineId > 0)
                {
                    ltTitle.Text = "Sửa thông tin online";
                    BindOnline(OnlineId);
                }
            }
        }

        private void BindOnline(int id)
        {
            var o = OnlineController.Online_GetById(id);
            if (o != null)
            {
                txtName.Text          = o.Name;
                txtYahoo.Text         = o.Yahoo;
                txtYahooName.Text     = o.YahooName;
                txtSkype.Text         = o.Skype;
                txtSkypeName.Text     = o.SkypeName;
                txtPhoneNo.Text       = o.PhoneNo;
                txtEmail.Text         = o.Email;
                txtPriority.Text      = o.Priority.ToString();
                ddlType.SelectedValue = o.TypeId.ToString();                
            }
        }
                
        protected void Save(object sender, EventArgs e)
        {
            OnlineObject o;
            if (OnlineId > 0)
            {
                o = OnlineController.Online_GetById(OnlineId);
                o.OnlineId  = OnlineId;
                o.TypeId    = ConvertUtility.ToInt32(ddlType.SelectedValue);
                o.Priority  = ConvertUtility.ToInt32(txtPriority.Text);
                o.Name      = txtName.Text;
                o.Yahoo     = txtYahoo.Text;
                o.YahooName = txtYahooName.Text;
                o.Skype     = txtSkype.Text;
                o.SkypeName = txtSkypeName.Text;
                o.PhoneNo   = txtPhoneNo.Text;
                o.Email     = txtEmail.Text;

                OnlineController.Online_Update(o);                
            }
            else
            {
                o = new OnlineObject();
                
                o.TypeId    = ConvertUtility.ToInt32(ddlType.SelectedValue);
                o.Priority  = ConvertUtility.ToInt32(txtPriority.Text);
                o.Name      = txtName.Text;
                o.Yahoo     = txtYahoo.Text;
                o.YahooName = txtYahooName.Text;
                o.Skype     = txtSkype.Text;
                o.SkypeName = txtSkypeName.Text;
                o.PhoneNo   = txtPhoneNo.Text;
                o.Email     = txtEmail.Text;

                OnlineController.Online_Create(o);
            }

            Response.Redirect(UrlHelpers.ListOnline);
        }
    }
}